import 'package:flutter/material.dart';
import 'package:flutter_shop/model/cartInfo.dart';
import 'package:provide/provide.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class CartProvide with ChangeNotifier{

  String cartString ='[]';
  List<CartInfoMode> cartList=[]; //商品列表对象

  //总价格
  double AllPrice=0;
  int AllGoodsCount=0;
  //是否全选
  bool isAllChange=true;

  //增加购物车
  save({goodsId,goodsName,count,price,images}) async{
    //初始化SharedPreferences
    SharedPreferences prefs = await  SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');  //获取持久化存储的值
    var temp=cartString==null?[]:json.decode(cartString.toString());
    //把获得值转变成List
    List<Map> tempList= (temp as List).cast();
    //声明变量，用于判断购物车中是否已经存在此商品ID
    var isHave= false;  //默认为没有
    int ival=0; //用于进行循环的索引使用
    AllPrice=0;
    AllGoodsCount=0;  //把商品总数量设置为0
    tempList.forEach((item){//进行循环，找出是否已经存在该商品
      //如果存在，数量进行+1操作
      if(item['goodsId']==goodsId){
        tempList[ival]['count']=item['count']+1;
        cartList[ival].count++;
        isHave=true;
      }
      if(item['isCheck']){
        AllPrice+= (cartList[ival].price* cartList[ival].count);
        AllGoodsCount+= cartList[ival].count;
      }


      ival++;
    });
    //  如果没有，进行增加
    if(!isHave){
      Map<String, dynamic> newGoods={
        'goodsId':goodsId,
        'goodsName':goodsName,
        'count':count,
        'price':price,
        'images':images,
        'isCheck': true  //是否已经选择
      };
      tempList.add(newGoods);
      cartList.add(new CartInfoMode.fromJson(newGoods));
      AllPrice+= (count * price);
      AllGoodsCount+=count;
    }
    //把字符串进行encode操作，
    cartString= json.encode(tempList).toString();

    prefs.setString('cartInfo', cartString);//进行持久化
    notifyListeners();
  }

  //清空购物车
  remo () async{
    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    sharedPreferences.remove('cartInfo');
    cartString='[]';
    cartList=[];
    notifyListeners();
  }

  ///查询购物车数据
  getCartInfo() async{

    SharedPreferences sharedPreferences= await SharedPreferences.getInstance();
    cartString=sharedPreferences.getString('cartInfo');
    cartList=[];
    if(cartString==null){
      cartList=[];
    }else{
      List<Map> tempList= (json.decode(cartString.toString()) as List).cast();
       AllPrice=0;
       AllGoodsCount=0;
      isAllChange=true;
      tempList.forEach((item){

        if(item['isCheck']){
          AllPrice+=(item['count']*item['price']);
          AllGoodsCount+=item['count'];
        }else{
          isAllChange=false;
        }

        cartList.add(CartInfoMode.fromJson(item));
      });
    }
    notifyListeners();
  }

  ///删除单个购物车商品
  deleteOneGoods(String goodsId)async{

    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    cartString=sharedPreferences.getString('cartInfo');

    List<Map> tempList=(json.decode(cartString.toString())as List).cast();

    int indextemp=0;
    int deleteindex=0;


    tempList.forEach((item){
      if(item['goodsId']==goodsId){
        deleteindex=indextemp;
      }
      indextemp++;
    });

    tempList.removeAt(deleteindex);

    cartString=json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    await getCartInfo();
  }

  ///单个商品选中
  changeCheckState(CartInfoMode cartInfoMode)async{
    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    cartString=sharedPreferences.getString('cartInfo');

    List<Map> tempList=(json.decode(cartString.toString())as List).cast();

    //临时索引
    int indextemp=0;
    //更换索引
    int updateindex=0;

    //循环所有商品进行对比改变
    tempList.forEach((item){
      if(item['goodsId']==cartInfoMode.goodsId){
        updateindex=indextemp;
      }
      indextemp++;
    });
    tempList[updateindex]['isCheck']?tempList[updateindex]['isCheck']=false:tempList[updateindex]['isCheck']=true;
    cartString=json.encode(tempList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    await getCartInfo();
  }


  ///全选和取消全选
  changeAll()async{

    SharedPreferences sharedPreferences=await SharedPreferences.getInstance();
    cartString=sharedPreferences.getString('cartInfo');
    List<Map> tempList=(json.decode(cartString.toString())as List).cast();

    List<Map> newList=[];
    for(var item in tempList ){
      var newItem = item;
      isAllChange?newItem['isCheck']=!isAllChange:newItem['isCheck']=!isAllChange;
      newList.add(newItem);
    }
    cartString= json.encode(newList).toString();
    sharedPreferences.setString('cartInfo', cartString);//
    await getCartInfo();
  }

  //操作商品数量
  addOrReduceAction(CartInfoMode cartInfoMode,String todo) async{

    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString=prefs.getString('cartInfo');
    List<Map> tempList= (json.decode(cartString.toString()) as List).cast();
    int tempIndex =0;
    int changeIndex=0;
    tempList.forEach((item){
      if(item['goodsId']==cartInfoMode.goodsId){
        changeIndex=tempIndex;
      }
      tempIndex++;
    });
    if(todo=='add'){
      cartInfoMode.count++;
    }else if(cartInfoMode.count>1){
      cartInfoMode.count--;
    }
    tempList[changeIndex]=cartInfoMode.toJson();
    cartString= json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);//
    await getCartInfo();

  }

}